# -*- coding: utf-8 -*-
# @Time    : 2024/5/10 15:12
# @Author  : Alvin
# @File    : utils.py
import execjs
import os
import json
import time
import random
import math
def generate_headers(api, data):
        # current_dir = os.path.dirname(os.path.abspath(__file__))
        #
        # # 构建 index.js 的绝对路径
        # index_js_path = os.path.join(current_dir, 'index.js')
        script_dir = os.path.dirname(os.path.realpath(__file__))

        # 构建相对路径
        # index_js_path = os.path.join(script_dir, 'commons', 'index.js')
        index_js_path = r"/app/scrapy_service/scrapy_service/commons/index.js"

        # 使用绝对路径打开 index.js 文件
        with open(index_js_path, 'r', encoding='utf-8') as f:
            js_code = f.read()

        result = execjs.compile(
            js_code).call('sign', api, data)
        headers = {
            'user-agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/121.0.0.0 Safari/537.36',
            'x-b3-traceid': result['traceId'],
            'x-s': result['xs'],
            'x-s-common': result['xsCommon'],
            'x-t': str(result['xt']),
            'authority': 'edith.xiaohongshu.com',
            'accept': 'application/json,*/*',
            'accept-language': 'zh-CN,zh;q=0.9',
            'cache-control': 'no-cache',
            'content-type': 'application/json;charset=UTF-8',
            'origin': 'https://www.xiaohongshu.com',
            'pragma': 'no-cache',
            'referer': 'https://www.xiaohongshu.com/',
            'sec-ch-ua': '"Not A(Brand";v="99", "Google Chrome";v="121", "Chromium";v="121"',
            'sec-ch-ua-mobile': '?0',
            'sec-ch-ua-platform': '"Windows"',
            'sec-fetch-dest': 'empty',
            'sec-fetch-mode': 'cors',
            'sec-fetch-site': 'same-site',
        }
        cookies = cookie_string_to_dict(result['cookie'])
        return headers,cookies
def cookie_string_to_dict(cookie_str):
    cookie_dict = {}
    # 通过分号分割 cookie 字符串，得到各个键值对
    cookie_pairs = cookie_str.split(';')
    for pair in cookie_pairs:
        # 忽略空字符串（可能由于尾部有分号引起）
        if pair.strip() == '':
            continue
        # 分割每个键值对，确保只取第一个'='之后的值，防止有些值中可能包含'='
        key, value = pair.split('=', 1)
        cookie_dict[key.strip()] = value.strip()
    return cookie_dict

def F():
    timestamp = str(math.floor(time.time() * 1000))
    if len(timestamp) < 13:
        timestamp = timestamp.ljust(13, "0")
    return timestamp

def J():
    t = int(F())
    r = random.randint(1, 2147483646)
    t <<= 64
    t += r
    return base36encode(t)

def base36encode(number):
    digits = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ"
    base36 = ""
    while number:
        number, i = divmod(number, 36)
        base36 = digits[i] + base36
    return base36.lower()

def get_json_data(json_str):
    try:
        json_obj = json.loads(json_str)
        return json.dumps(json_obj, indent=2, ensure_ascii=False)
    except json.JSONDecodeError as e:
        print(f"JSON decoding error: {e}")
        return json_str  # 返回原始字符串作为备选方案
if __name__ == '__main__':
    print(get_json_data({
        "source_note_id": "6631193c000000001e036b26",
        "image_formats": ["jpg", "webp", "avif"],
        "extra": {"need_body_topic": "1"}
}))